package com.goodomen.garbage.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

public class AESEncrypter {

	private static String encrypt(String msg, String skey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");//需要自己手动设置
        random.setSeed(skey.getBytes());  
		kgen.init(128, random);
		SecretKey key = kgen.generateKey();
		Cipher ecipher = Cipher.getInstance("AES");
		ecipher.init(Cipher.ENCRYPT_MODE, key);
		return asHex(ecipher.doFinal(msg.getBytes()));
	}

	private static String decrypt(String value, String skey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");//需要自己手动设置
        random.setSeed(skey.getBytes());  
		kgen.init(128, random);
		SecretKey key = kgen.generateKey();
		Cipher dcipher = Cipher.getInstance("AES");
		dcipher.init(Cipher.DECRYPT_MODE, key);
		return new String(dcipher.doFinal(asBin(value)));
	}

	private static String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		for (int i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10)
				strbuf.append("0");
			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}
		return strbuf.toString();
	}

	private static byte[] asBin(String src) {
		if (src.length() < 1)
			return null;
		byte[] encrypted = new byte[src.length() / 2];
		for (int i = 0; i < src.length() / 2; i++) {
			int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);

			encrypted[i] = (byte) (high * 16 + low);
		}
		return encrypted;
	}
	
	/**
	 * 加密
	 * @param sSrc
	 * @param skey
	 * @return
	 */
	public static String getEncrypt(String sSrc, String skey) {
		if(StringUtils.isNotBlank(sSrc)) {
			try {
				sSrc = encodeBase64(sSrc);
				return encrypt(sSrc, skey);
			} catch (Exception e) {

			}
		}
		return null;	
	}
	
	/**
	 * 解密
	 * @param sSrc
	 * @param skey
	 * @return
	 */
	public static String getDecrypt(String sSrc, String skey) {
		if(StringUtils.isNotBlank(sSrc)) {
			try {
				sSrc = decrypt(sSrc, skey);
				return decodeBase64(sSrc);
			} catch (Exception e) {

			}
		}
		return null;
	}
	
	private static String encodeBase64(String str) throws UnsupportedEncodingException {
		return new String(Base64.encodeBase64(str.getBytes("utf8")));
	}
	
	private static String decodeBase64(String str) throws UnsupportedEncodingException {
		return new String(Base64.decodeBase64(str), "utf8");
	}
}
